import React, { useEffect, useState } from 'react';
import { useSearchParams } from 'react-router-dom';
import Header from '../Header';
import Footer from '../Footer';
import { Card } from 'antd';
import './index.css';
import { fetchGoodsData } from '../../../../apis/goods';

export default function SearchPage() {
  const { Meta } = Card;
  const [searchParams] = useSearchParams();
  const keyword = searchParams.get('keyword');

  const [goodsData, setGoodsData] = useState([]);
  const [matchingGoods, setMatchingGoods] = useState([]);

  useEffect(() => {
    const fetchData = async () => {
      const data = await fetchGoodsData();
      setGoodsData(data);
    };

    fetchData();
  }, []);

  useEffect(() => {
    const matchingGoods = goodsData.filter(
      (goods) =>
        goods.name.toLowerCase().includes(keyword.toLowerCase())
    ).slice(0, 4);
    setMatchingGoods(matchingGoods);
  }, [keyword, goodsData]);

  return (
    <div>
      <Header></Header>
   <div className='hd_searchpage'>
      <p>搜索内容为: {keyword}</p>
       <p>以下是搜索结果：</p>
   </div>
      <div className='list'>
        {matchingGoods.map((goods) => (
          <Card
            key={goods.id}
            className='card'
            hoverable
            style={{
              width: 250,
            }}
            cover={
              <img alt={goods.name} src={require(`../../../../static/image/` + goods.images[0])} />
            }
          >
            <Meta className='txt' title={goods.name} />
            <div className='txt_item'>
              <h3>￥{goods.price}</h3>
              <p>销量：{goods.sales}</p>
            </div>
          </Card>
        ))}
      </div>

     
      <Footer></Footer>
    </div>
  );
}
